package com.killers.cold.exception;

import java.text.MessageFormat;

/**
 * 服务异常，由微服务内部逻辑导致的错误请抛出此异常。
 */
public class ServiceException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    private int code;
    /**
     * 可替换变量,相当于占位符
     */
    private Object[] variables = null;

    public ServiceException(int code) {
        this.code = code;
    }

    public ServiceException(int code, String message) {
        super(message);
        this.code = code;
    }

    public ServiceException(IErrorCodeType errorCodeType){
        super(errorCodeType.getMessage());
        this.code = errorCodeType.getCode();
    }

    /**
     * 错误信息可配置成带占位符的变量， 可变参数将填充占位符
     *
     * @param type the errorCodeType
     * @param args the args
     */
    public ServiceException(IErrorCodeType errorCodeType, Object... args) {
        super(MessageFormat.format(errorCodeType.getMessage(), args));
        this.code = errorCodeType.getCode();
    }

    public ServiceException(int code, String message, Throwable e) {
        super(message, e);
        this.code = code;
    }

    public ServiceException(int code, String message, Object[] variables) {
        super(message);
        this.code = code;
        if (variables != null) {
            this.variables = variables.clone();
        }
    }

    public Object[] getVariable() {
        if (variables != null) {
            return variables.clone();
        } else {
            return null;
        }
    }

    /**
     * @return the code
     */
    public int getCode() {
        return code;
    }

    /**
     * @param code the code to set
     */
    public void setCode(int code) {
        this.code = code;
    }

    /**
     * 异常堆栈增加错误代码和绑定变量
     */
    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append(this.getMessage()).append("[").append(this.code).append("]\n");
        if (variables != null && variables.length != 0) {
            sb.append("绑定变量[");
            for (int i = 0; i < variables.length; i++) {
                sb.append(variables[i].toString());
            }
            sb.append("]\n");
        }
        sb.append(super.toString());
        return sb.toString();
    }
}
